<?php
/*
 * Threads
 */
class ThreadsController extends Zend_Controller_Action
{
	private $registry; // registry
	private $auth; // user-values
	
	public function init()
	{
		// Zend_Registry instanzieren und global vergeben
		$registry = Zend_Registry::getInstance();
		$this->registry = $registry;
		
		// Zend_Auth instanzieren und global vergeben
		$auth = Zend_Auth::getInstance();
    	$this->view->auth = $auth->hasIdentity();
    	
    	// Benutzerüberprüfung
    	if($auth->hasIdentity())
    	{
    		$this->view->auth_role 			= $auth->getIdentity()->role;
    		$this->view->username 			= $auth->getIdentity()->username;
    		$this->view->auth_uid			= $auth->getIdentity()->uid;
    		$this->view->unread_messages	= $auth->getIdentity()->count_unread_messages;
    	}
    	else
    	{
    		$this->view->username 	= 'Gast';
    	}

    	$this->auth = $auth;
    	
    	// lang
		$this->view->translate = Zend_Registry::get('lang');
		
		// flash messenger
		$this->view->flashMessenger	= $this->_helper->FlashMessenger;
	}
	
	
	
	/*
	 * displays all threads in a board
	 * 
	 * @param null
	 * 
	 * @return the content
	 */
	public function indexAction()
	{
		// settings
		$settings	= Zend_Registry::getInstance()->get('settings');
		
		// params
		$uid 		= intval($this->getRequest()->getParam('uid', 0));
		$page 		= intval($this->getRequest()->getParam('page', 0));
		$count		= $this->auth->hasIdentity() ? $this->auth->getIdentity()->threads_per_page : $settings['threads_per_page']; 
		
		// helper
		$baseUrl	= new MHDEV_View_Helper_BaseUrl();
		$url		= new Zend_View_Helper_Url();
		$isMod		= new MHDEV_View_Helper_IsMod();
		
		// db
		$threads	= new Threads();
		$boards		= new Boards();
		
		// query
		if($this->auth->hasIdentity() && $isMod->IsMod($this->auth->getIdentity()->uid, $uid))
		{
			$query	= $threads->fetchAll('board_uid =' . $uid, array('is_sticky DESC', 'last_reply_date DESC'));
		}
		else
		{
			$query	= $threads->fetchAll('is_public = 1 AND is_deleted = 0 AND board_uid =' . $uid, array('is_sticky DESC', 'last_reply_date DESC'));
		}

		$getBoard	= $boards->find($uid);
		if($getBoard->count() > 0)
		{
			$resBoard 	= $getBoard->toArray();
			$is_public	= $resBoard[0]['is_public'];
		}
		
		// paginator
		$paginator	= Zend_Paginator::factory($query->toArray());
        $paginator->setItemCountPerPage($count);
        $paginator->setCurrentPageNumber($page);
        
		// view
		$this->view->result_count	= $query->count();
		$this->view->result			= $paginator;
		$this->view->board_uid		= $uid;
		$this->view->is_public		= $is_public;
	}
	
	
	
	/*
	 * add a new thread
	 * 
	 * @param null
	 * 
	 * @return the content with the form
	 */
	public function addAction()
	{
		// init editor
		$this->initEditor();
		
		// helper
		$url			= new Zend_View_Helper_Url();
		$baseUrl		= new MHDEV_View_Helper_BaseUrl();
		
		// param
		$uid 			= intval($this->getRequest()->getParam('uid', 0));
		
		//forms
		$new_thread 	= new NewThreadForm();
		
		// db
		$boards			= new Boards();
		$threads		= new Threads();
		
		if($this->auth->hasIdentity())
		{
			$user_uid		= $this->auth->getIdentity()->uid;
			$getPubThreads	= $threads->fetchAll('is_public = 1 AND user_uid =' . $user_uid);
			$pubThreads		= $getPubThreads->count();
		}
		else
		{
			$pubThreads 	= 0;
		}
		
		$getGuestPerm	= $boards->find($uid);
		
		if($getGuestPerm->count() > 0)
		{
			$arrayGuestPerm = $getGuestPerm->toArray();
			$this->view->allow_guest_threads = $arrayGuestPerm[0]['allow_guest_threads'];
			
			// add captcha-field to non-registered-user
			if(!$this->auth->hasIdentity() && $arrayGuestPerm[0]['allow_guest_threads'] == 1)
			{
				$captcha = new Zend_Form_Element_Captcha('captcha', array(
		            'label' => Zend_Registry::get('lang')->_('captcha'),
		            'captcha' => array(
		                'captcha' => 'Image',
		                'wordLen' => 6,
		                'timeout' => 300,
		                'width' => 200,
		                'heigth' => 150,
		                'imgDir' => 'static/gfx/captcha/',
		                'imgUrl' => $baseUrl->BaseUrl() . '/static/gfx/captcha/',
		                'font' => 'static/gfx/captcha/fonts/gautami.ttf',
		                'fontsize' => 28,
		        		'messages' => array(
		                    'badCaptcha' 	=> Zend_Registry::get('lang')->_('error_captcha'),
		                    'missingID' 	=> Zend_Registry::get('lang')->_('error_captcha'),
		                    'missingValue' 	=> Zend_Registry::get('lang')->_('error_captcha')
		                )
		            )
		        ));
		        
		        $new_thread->addElement($captcha, 'captcha', array('order' => 2));
		        $this->view->captcha = $new_thread->getElement('captcha');
			}
		}
		
		// get form-data
		if($this->getRequest()->isPost())
		{
			if($new_thread->isValid($_POST))
			{
				if($thread_uid = $this->newThread($new_thread, $uid, $pubThreads))
				{
					$this->_redirect('/posts/' . $thread_uid . '.html');
				}
				else
				{
					$new_thread->populate($_POST);
				}
			}
			else
			{
				$this->view->errorMessage = Zend_Registry::get('lang')->_('error_threads_form');
				$new_thread->populate($_POST);
			}
		}
		
		$this->view->pubThreads = $pubThreads;
	}
	
	
	/*
	 * create a new thread
	 * 
	 * @param Zend_Form $form
	 * @param int $uid
	 * @param int $pubThreads
	 * 
	 * @return int $thread_uid
	 */
	public function newThread($form, $uid, $pubThreads)
	{
		// db
		$threads	= new Threads();
		$posts 		= new Posts();
		$boards		= new Boards();
		$user		= new User();
		
		// form		
		$values 	= $form->getValues();
		
		// params
		$user_uid	= $this->auth->getIdentity()->uid > 0 ? $this->auth->getIdentity()->uid : 0;
		
		// prepare thread array
		$newThreadArray = array(
			'board_uid' 			=> $uid, 
			'user_uid' 				=> $user_uid, 
			'create_date'			=> new Zend_Db_Expr("NOW()"),
			'last_reply_date'		=> new Zend_Db_Expr("NOW()"),
			'last_reply_user_uid'	=> $user_uid,
			'count_hits'			=> 1,
			'title'					=> trim($values['title']),
		);
		
		if($pubThreads > 0)
		{
			// set thread public when user has allready one or more public threads
			$newThreadArray['is_public'] = 1;
		}
		
		// insert thread in the database and get insert_id
		$thread_uid = $threads->insert($newThreadArray);
		
		// prepare post array
		$newPostArray	= array(
			'thread_uid'	=> $thread_uid,
			'user_uid'		=> $user_uid,
			'title'			=> trim($values['title']),
			'text'			=> $values['text'],
			'create_date'	=> new Zend_Db_Expr("NOW()"),
			'is_public'		=> 1
		);
		
		// insert post in database and get insert_id
		$post_uid = $posts->insert($newPostArray);
		
		// prepare board update array
		$boardUpdateArray = array(
			'count_threads' 	=> new Zend_Db_Expr('count_threads+1'),
			'count_posts'		=> new Zend_Db_Expr('count_posts+1'),
			'last_thread_uid'	=> $thread_uid,
			'last_post_uid'		=> $post_uid
		);
		
		// update board
		$boards->update($boardUpdateArray, 'uid = ' . $uid);
		
		// check if board a sub board
		$rootCheck	= $boards->find($uid);
		if($rootCheck->count() > 0)
		{
			// array with database results
			$arrayRootCheck = $rootCheck->toArray();
			
			// have a root uid?
			if($arrayRootCheck[0]['root_uid'] > 0)
			{
				// update root board
				$boards->update($boardUpdateArray, 'uid =' . $arrayRootCheck[0]['root_uid']);
			}
		}
		
		// if user is logged in
		if($this->auth->hasIdentity())
		{
			// update user post and thread count
			$userUpdateArray = array(
				'count_threads'	=> new Zend_Db_Expr('count_threads+1'),
				'count_posts'	=> new Zend_Db_Expr('count_posts+1'),
			);
			$user->update($userUpdateArray, 'uid=' . $user_uid);
		}
		
		// return insert_id from the thread
		return $thread_uid;
	}
	
	
	
	/*
	 * update thread title
	 * 
	 * @param null
	 * 
	 * @return string topic_title
	 */
	public function settitleAction()
	{
		Zend_Layout::getMvcInstance()->disableLayout();
		
		// params
		$uid 		= intval($this->getRequest()->getParam('uid', 0));
		$value		= $this->getRequest()->getParam('val', false);
		
		// db
		$threads	= new Threads();
		
		// helper
		$check		= new MHDEV_View_Helper_IsMod();
		
		// query
		$getThread	= $threads->find($uid);
		
		if($getThread->count() > 0)
		{
			$resThread = $getThread->toArray();
			if($check->IsMod($this->auth->getIdentity()->uid, $resThread[0]['board_uid']))
			{
				$threads->update(array('title' => $value), 'uid=' . $uid);
				return print $value;
			}
		}
	}
	
	
	
	/*
	 * Watch a thread or stop watching ...
	 */
	public function watchAction()
	{
		// disable layout
		Zend_Layout::getMvcInstance()->disableLayout();
		
		// params
		$thread_uid	= intval($this->getRequest()->getParam('thread_uid', 0));
		$user_uid	= intval($this->getRequest()->getParam('user_uid', 0));
		$status		= $this->getRequest()->getParam('status', false);
		
		// helper
		$access		= new MHDEV_View_Helper_HasAccess();
		
		// db
		$notice 	= new ThreadsNotice();
		$threads	= new Threads();
		
		// get thread
		$getThread	= $threads->find($thread_uid);
		
		if($getThread->count() > 0)
		{
			$resThread	= $getThread->toArray();
			
			// check permissions
			if($resThread[0]['is_public'] == 0 && !$access->HasAccess($resThread[0]['board_uid']))
			{
				// no permission on this thread ...
			}
			else
			{
				if($status == 'activate')
				{
					$notice->insert(array(
						'thread_uid'	=> $thread_uid,
						'user_uid'		=> $user_uid,
						'last_post'		=> new Zend_Db_Expr('NOW()')
					));
					$this->view->status = 'activate';
				}
				elseif($status == 'stop')
				{
					$notice->delete('thread_uid = ' . $thread_uid . ' AND user_uid = ' . $user_uid);
					$this->view->status = 'stop';
				}
			}
		}
	}
	
	
	
	/*
	 * add javascript to the doc-head for the bbcode-editor
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function initEditor()
	{
		$baseurl = new MHDEV_View_Helper_BaseUrl();
		#$this->view->headScript()->appendScript('var basePath = \'' . $baseurl->BaseUrl() . '\';');
		$this->view->headScript()->appendFile($baseurl->BaseUrl() . '/static/js/editor.js');
	}
	
	
	
	/*
	 * Set a thread public
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function setpublicAction()
	{
		// helper
		$mod		= new MHDEV_View_Helper_IsMod();
		$url		= new Zend_View_Helper_Url();
		$clean		= new MHDEV_View_Helper_CleanUrlTitle();
		
		// params
		$uid		= $this->_request->getParam('uid', 0);

		// db
		$threads	= new Threads();
		$boards		= new Boards();
		
		// query
		$getThread	= $threads->find($uid);
		
		// check if thread is not yet deleted ...
		if($getThread->count() > 0)
		{
			$resThread	= $getThread->toArray();
			
			// check if user is a mod or admin ...
			if($mod->IsMod($this->auth->getIdentity()->uid, $resThread[0]['board_uid']))
			{
				$getBoard	= $boards->find($resThread[0]['board_uid']);
				
				// check if board is available
				if($getBoard->count() > 0)
				{
					$resBoard	= $getBoard->toArray();
					
					// prepare redirect
					$redirect 	= $url->url(array('controller' => 'threads', 'uid' => $resThread[0]['board_uid'], 'title' => $this->view->escape($clean->CleanUrlTitle($resBoard[0]['title']))), 'boards', true);
					
					// update thread and set him public
					$threads->update(array('is_public' => 1), 'uid = ' . intval($uid));
					
					// redirect
					$this->_redirect('/threads/' . $resThread[0]['board_uid'] . '-' . $this->view->escape($clean->CleanUrlTitle($resBoard[0]['title'])) . '.html');
				}
			}
			else
			{
				$this->_redirect('/');
			}
		}
		else
		{
			$this->_redirect('/');
		}
	}
	
	
	
	/*
	 * Move a topic to a other board
	 * 
	 * @param null
	 * 
	 * @return null
	 */
	public function moveAction()
	{
		// post
		$postData	= $this->_request->getPost();
		
		// vars
		$topic_uid	= intval($postData['topic_uid']);
		$board_uid	= intval($postData['board_uid']);
		
		// db
		$threads	= new Threads();
		$posts		= new Posts();
		
		// helper
		$mod		= new MHDEV_View_Helper_IsMod();
		
		if($topic_uid > 0 && $board_uid > 0)
		{
			$getThread	= $threads->find($topic_uid);

			if($getThread->count() > 0)
			{
				$resThread	= $getThread->toArray();
				
				if($mod->IsMod($this->auth->getIdentity()->uid, $resThread[0]['board_uid']))
				{
					unset($resThread[0]['uid']);
					$new_topic = $threads->insert($resThread[0]);
					
					// update threads
					$threads->update(array('moved_uid' => $new_topic), 'uid=' . $topic_uid);
					$threads->update(array('board_uid' => $board_uid), 'uid=' . $new_topic);
					
					// update posts
					$posts->update(array('thread_uid' => $new_topic), 'thread_uid =' . $topic_uid);
					
					// status message
					$this->_helper->FlashMessenger($this->registry->get('lang')->_('flash_topic_moved'));
					
					// redirect
					$this->_redirect('/posts/' . $new_topic . '.html');
				}
				else
				{
					// status message
					$this->_helper->FlashMessenger($this->registry->get('lang')->_('flash_topic_moved_e1'));
					
					// redirect
					$this->_redirect('/posts/' . $topic_uid . '.html');
				}
			}
			else
			{
				$this->_redirect('/');
			}
		}
		else
		{
			$this->_redirect('/');
		}
	}
	
}
?>